<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>测试管理</span>
        </div>
      </template>
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="测试标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入测试标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="测试类别" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择测试类别" clearable style="width: 240px">
          <el-option label="心理健康" value="心理健康" />
          <el-option label="职业规划" value="职业规划" />
          <el-option label="人格测试" value="人格测试" />
          <el-option label="学习能力" value="学习能力" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="testList"
      border
    >
      <el-table-column label="测试标题" prop="title" />
      <el-table-column label="测试类别" prop="category" />
      <el-table-column label="预计用时" prop="estimatedTime">
        <template #default="{ row }">
          {{ row.estimatedTime }}分钟
        </template>
      </el-table-column>
      <el-table-column label="题目数量" prop="questionCount">
        <template #default="{ row }">
          {{ row.questions ? row.questions.length : 0 }}
        </template>
      </el-table-column>
      <el-table-column label="难度等级" prop="difficulty">
        <template #default="{ row }">
          <el-tag :type="row.difficulty === 1 ? 'success' : row.difficulty === 2 ? 'warning' : 'danger'">
            {{ row.difficulty === 1 ? '简单' : row.difficulty === 2 ? '中等' : '困难' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="(val) => handleStatusChange(row, val)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180" />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">修改</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-if="total > 0"
      :total="total"
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 30, 50]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper"
    />

    <!-- 添加/修改对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="测试标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入测试标题" />
        </el-form-item>
        <el-form-item label="测试描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入测试描述"
          />
        </el-form-item>
        <el-form-item label="预计用时" prop="estimatedTime">
          <el-input-number
            v-model="form.estimatedTime"
            :min="1"
            :max="180"
            placeholder="请输入预计用时(分钟)"
          />
        </el-form-item>
        <el-form-item label="总分" prop="totalScore">
          <el-input-number
            v-model="form.totalScore"
            :min="1"
            :max="1000"
            placeholder="请输入总分"
          />
        </el-form-item>
        <el-form-item label="测试类别" prop="category">
          <el-select v-model="form.category" placeholder="请选择测试类别">
            <el-option label="心理健康" value="心理健康" />
            <el-option label="职业规划" value="职业规划" />
            <el-option label="人格测试" value="人格测试" />
            <el-option label="学习能力" value="学习能力" />
          </el-select>
        </el-form-item>
        <el-form-item label="测试类型" prop="testType">
          <el-select v-model="form.testType" placeholder="请选择测试类型">
            <el-option label="SDS抑郁量表" value="SDS" />
            <el-option label="SAS焦虑量表" value="SAS" />
            <el-option label="MBTI性格测试" value="MBTI" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度等级" prop="difficulty">
          <el-select v-model="form.difficulty" placeholder="请选择难度等级">
            <el-option label="简单" :value="1" />
            <el-option label="中等" :value="2" />
            <el-option label="困难" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否必修">
          <el-switch v-model="form.isRequired" />
        </el-form-item>
        <el-form-item label="结果模板">
          <el-input
            v-model="form.resultTemplate"
            type="textarea"
            placeholder="请输入结果解释模板"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="评分方式" prop="scoringType">
          <el-select v-model="form.scoringType" placeholder="请选择评分方式">
            <el-option label="维度评分" value="DIMENSION" />
            <el-option label="总分评分" value="TOTAL" />
            <el-option label="性格分类" value="PERSONALITY" />
          </el-select>
        </el-form-item>
        <el-form-item label="维度配置" prop="dimensionConfig">
          <el-input
            v-model="form.dimensionConfig"
            type="textarea"
            placeholder="请输入维度配置"
            :rows="10"
            :autosize="{ minRows: 10, maxRows: 20 }"
          />
          <div class="form-tip">
            <p>维度配置格式：JSON格式，包含维度列表和标准化系数</p>
            <el-button 
              type="primary" 
              link 
              @click="fillDimensionConfigTemplate"
            >
              填充模板
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { 
  listTests, 
  addTest, 
  updateTest, 
  deleteTest, 
  updateTestStatus 
} from '@/api/psychological-test'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'TestManage',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: '',
        category: '',
        status: null
      },
      // 测试列表数据
      testList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 对话框显示状态
      dialog: {
        visible: false,
        title: '',
        type: 'add'  // add or edit
      },
      // 表单数据
      form: {
        title: '',
        description: '',
        estimatedTime: 30,
        totalScore: 100,
        category: '',
        testType: '',
        difficulty: 2,
        isRequired: false,
        status: 1,
        resultTemplate: '',
        scoringType: 'DIMENSION',
        dimensionConfig: ''
      },
      // 表单校验规则
      rules: {
        title: [
          { required: true, message: '请输入测试标题', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入测试描述', trigger: 'blur' }
        ],
        estimatedTime: [
          { required: true, message: '请输入预计用时', trigger: 'blur' }
        ],
        totalScore: [
          { required: true, message: '请输入总分', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择测试类别', trigger: 'change' }
        ],
        testType: [
          { required: true, message: '请选择测试类型', trigger: 'change' }
        ],
        scoringType: [
          { required: true, message: '请选择评分方式', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度等级', trigger: 'change' }
        ]
      },
      // 添加编辑ID字段
      editId: null,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询测试列表 */
    async getList() {
      this.loading = true
      try {
        const response = await listTests(this.queryParams)
        if (response.code === 200) {
          this.testList = response.data.records
          this.total = response.data.total
        } else {
          throw new Error(response.msg || '获取列表失败')
        }
      } catch (error) {
        console.error('获取列表异常:', error)
        ElMessage.error(error.message || '获取列表失败，请重试')
      } finally {
        this.loading = false
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        title: '',
        category: '',
        status: null
      }
      this.getList()
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.dialog.type = 'add'
      this.dialog.title = '添加测试'
      this.dialog.visible = true
      this.form = {
        title: '',
        description: '',
        estimatedTime: 30,
        totalScore: 100,
        category: '',
        testType: '',
        difficulty: 2,
        isRequired: false,
        status: 1,
        resultTemplate: '',
        scoringType: 'DIMENSION',
        dimensionConfig: ''
      }
    },

    /** 修改按钮操作 */
    handleEdit(row) {
      this.dialog.type = 'edit'
      this.dialog.title = '修改测试'
      this.dialog.visible = true
      this.editId = row.id
      const dimensionConfig = typeof row.dimensionConfig === 'string' 
        ? row.dimensionConfig 
        : JSON.stringify(row.dimensionConfig, null, 2)

      this.form = {
        title: row.title,
        description: row.description,
        estimatedTime: row.estimatedTime,
        totalScore: row.totalScore,
        category: row.category,
        testType: row.testType,
        difficulty: row.difficulty,
        isRequired: row.isRequired,
        resultTemplate: row.resultTemplate,
        scoringType: row.scoringType,
        dimensionConfig: dimensionConfig
      }
    },

    /** 填充维度配置模板 */
    fillDimensionConfigTemplate() {
      const template = {
        dimensions: [
          { key: 'COGNITIVE', name: '认知症状', weight: 1.0 },
          { key: 'EMOTIONAL', name: '情感症状', weight: 1.0 },
          { key: 'SOMATIC', name: '躯体症状', weight: 1.0 },
          { key: 'PSYCHOMOTOR', name: '精神运动症状', weight: 1.0 }
        ],
        standardization: 1.25
      }
      this.form.dimensionConfig = JSON.stringify(template, null, 2)
    },

    /** 提交表单 */
    async submitForm() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        try {
          // 验证维度配置的JSON格式
          let parsedDimensionConfig = null
          if (this.form.dimensionConfig) {
            try {
              parsedDimensionConfig = JSON.parse(this.form.dimensionConfig)
            } catch (e) {
              ElMessage.error('维度配置必须是有效的JSON格式')
              return
            }
          }

          const submitData = {
            title: this.form.title,
            description: this.form.description,
            estimatedTime: this.form.estimatedTime,
            totalScore: this.form.totalScore,
            category: this.form.category,
            testType: this.form.testType,
            difficulty: this.form.difficulty,
            isRequired: this.form.isRequired,
            resultTemplate: this.form.resultTemplate,
            scoringType: this.form.scoringType,
            dimensionConfig: parsedDimensionConfig,
          }
          
          if (this.dialog.type === 'add') {
            const response = await addTest(submitData)
            if (response.code === 200) {
              ElMessage.success('添加成功')
              if (response.data) {
                await updateTestStatus(response.data, 1)
              }
              this.dialog.visible = false
              this.getList()
            } else {
              // throw new Error(response.msg || '添加失败')
            }
          } else {
            // 使用存储的测试ID进行更新
            const response = await updateTest(this.editId, submitData)
            if (response.code === 200) {
              ElMessage.success('修改成功')
              this.dialog.visible = false
              this.getList()
            } else {
              throw new Error(response.msg || '修改失败')
            }
          }
        } catch (error) {
          console.error('提交表单异常:', error)
          ElMessage.error(error.message || '操作失败，请重试')
        }
      })
    },

    /** 删除按钮操作 */
    async handleDelete(row) {
      try {
        await ElMessageBox.confirm('确认要删除该测试吗？', '警告', {
          type: 'warning'
        })
        const response = await deleteTest(row.id)
        if (response.code === 200) {
          ElMessage.success('删除成功')
          this.getList()
        } else {
          throw new Error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除异常:', error)
          ElMessage.error(error.message || '删除失败，请重试')
        }
      }
    },

    /** 启用/禁用按钮操作 */
    async handleStatusChange(row, newStatus) {
      const text = newStatus === 1 ? '启用' : '禁用'
      try {
        await ElMessageBox.confirm(`确认要${text}该测试吗？`, '提示', {
          type: 'warning'
        })
        const response = await updateTestStatus(row.id, newStatus)
        if (response.code === 200) {
          ElMessage.success(`${text}成功`)
          this.getList()
        } else {
          // 如果更新失败，恢复原来的状态
          row.status = newStatus === 1 ? 0 : 1
          throw new Error(response.msg || `${text}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          // 如果不是用户取消操作，恢复原来的状态
          row.status = newStatus === 1 ? 0 : 1
          console.error(`${text}异常:`, error)
          ElMessage.error(error.message || `${text}失败，请重试`)
        }
      }
    },

    /** 分页大小改变 */
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },

    /** 页码改变 */
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },
  }
}
</script>

<style scoped>
.app-container {
  height: calc(100vh - 84px);
  padding: 10px;
  background-color: #f0f2f5;
}
.mb8 {
  margin-bottom: 8px;
}
.dialog-footer {
  text-align: right;
}
.box-card {
  height: 100%;
  margin: -10px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.5;
}
</style> 